package com.example.passport.mapper;


import com.example.common.dto.Pagination;
import com.example.passport.dto.UserRoleDto;
import com.example.passport.entity.UserRole;
import org.apache.ibatis.annotations.*;

import java.util.List;

import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;


@Mapper
public interface UserRoleMapper {
    @Select("<script>" +
            "SELECT * FROM `user_role`" +
            "<where>" +
            "<if test='userRole.userId!=null'> AND `user_id`=#{userRole.userId}</if>" +
            "</where>" +
            " ORDER BY `created_at` DESC " +
            "</script>")
   List<UserRole> findById(@Param("userRole") UserRole userRole );

    @Insert("INSERT INTO `user_role`" +
            " (`tenant_id`,`user_id`,`role_id`) VALUES" +
            " (#{tenantId}, #{userId}, #{roleId})")
    void create(UserRole userRole);

    @Update("UPDATE `user_role` SET " +
            "`user_id` = #{userRole.userId} " +
            ",`role_id` = #{userRole.roleId} " +
            " WHERE `id`=#{userRole.id} AND `tenant_id`=#{userRole.tenantId}")
    int update(@Param("userRole") UserRole userRole);

    @Select("<script>" +
            "SELECT * FROM `user_role`" +
            "<where>" +
            "`tenant_id`=#{condition.tenantId} " +
            "<if test='condition.id!=null'> AND `id`=#{condition.id}</if>" +
            "<if test='condition.userId!=null'> AND `user_id`=#{condition.userId} </if>" +
            "<if test='condition.roleId!=null'> AND `role_id`=#{condition.roleId} </if>" +
            "</where>" +
            " ORDER BY `id` DESC LIMIT #{pagination.offset}, #{pagination.limit}" +
            "</script>")
    List<UserRole> findAll(@Param("condition") UserRoleDto condition, @Param("pagination") Pagination pagination);

    @Select("<script>" +
            "SELECT count(*) FROM `user_role`" +
            "<where>" +
            "`tenant_id`=#{condition.tenantId} " +
            "<if test='condition.id!=null'> AND `id`=#{condition.id}</if>" +
            "<if test='condition.userId!=null'> AND `user_id`=#{condition.userId} </if>" +
            "<if test='condition.roleId!=null'> AND `role_id`=#{condition.roleId} </if>" +
            "</where>" +
            "</script>")
    long count(@Param("condition") UserRoleDto condition);

    @Delete("DELETE FROM user_role WHERE id=#{id} AND tenant_id = #{tenantId}")
    int deleteById(long id, long tenantId);

    @Select("<script>" +
            "SELECT * FROM `user_role` WHERE `tenant_id` = #{tenantId}" +
            " AND `user_id` = #{userId}" +
            " AND `role_id` = #{roleId}" +
            "<if test='id!=null'> AND `id`!=#{id}</if>" +
            " LIMIT 1" +
            "</script>")
    UserRole findByUserRoleId(UserRole userRole);
}
